﻿using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Web;
using System.Web.Mvc;

namespace Portal.Web.Controllers
{
    public class ArticalController : BaseFrontController
    {
        private readonly IArticleRepository _articleRepository;

        public ArticalController(IArticleRepository articleRepository)
        {
            _articleRepository = articleRepository;
        }

        public ActionResult News(string name, string sort = "CreateTime", string order = "ASC", int page = 1, int rows = 7)
        {

            var model = CreateFrontViewData<FronArticalViewData>();
            model.List = _articleRepository.Get(o => o.Culture == Culture && (string.IsNullOrEmpty(name.NullSafe()) || o.MainTitle.Contains(name)) && o.CategoryId == ((int)CategoryArticleEnum.News).ToString(CultureInfo.InvariantCulture)).OrderByDescending(o => o.CreateTime).ToPagedList(page, rows);
            return View(model);
        }
        public ActionResult NewsDetail(string articalId)
        {
            var model = CreateFrontViewData<FronArticalViewData>();
            model.Model = _articleRepository.Get().SingleOrDefault(o => o.Id == articalId && o.Culture == Culture);
            if (model.Model == null)
                return NotFount();
            model.PrevModel =
                _articleRepository.Get(
                    o => o.CreateTime >= model.Model.CreateTime && o.Id != articalId && o.Culture == Culture).OrderBy(
                        o => o.CreateTime).
                    FirstOrDefault();
            model.NextModel =
                _articleRepository.Get(
                    o => o.CreateTime <= model.Model.CreateTime && o.Id != articalId && o.Culture == Culture).
                    OrderByDescending(o => o.CreateTime).
                    FirstOrDefault();
            Load(model.Model);
            return View(model);
        }

        public ActionResult NewsControl(string sort = "CreateTime", string order = "DESC")
        {
            var model = CreateFrontViewData<FrontNewsControlViewData>();
            model.FirstModel = _articleRepository.Get(o => o.Culture == Culture && o.CategoryId == ((int)CategoryArticleEnum.News).ToString(CultureInfo.InvariantCulture)).OrderByDescending(o => o.CreateTime).FirstOrDefault();
            model.List = _articleRepository.Get(o => o.Culture == Culture && o.CategoryId == ((int)CategoryArticleEnum.News).ToString(CultureInfo.InvariantCulture)).OrderByDescending(o => o.CreateTime).Skip(1).Take(3).ToList();
            return View(model);
        }

        public ActionResult TechnologyConsulting(string sort = "CreateTime", string order = "ASC", int page = 1, int rows = 10)
        {
            var model = CreateFrontViewData<FronArticalViewData>();
            model.List = _articleRepository.Get(o => o.Culture == Culture).OrderByDescending(o => o.CreateTime).ToPagedList(page, rows);
            return View(model);
        }
        public ActionResult TechnologyConsultingDetails(string articalId)
        {
            var model = CreateFrontViewData<FronArticalViewData>();
            model.Model = _articleRepository.Get().SingleOrDefault(o => o.Id == articalId && o.Culture == Culture);
            if (model.Model == null)
                return NotFount();
            model.PrevModel = _articleRepository.Get(o => o.CreateTime >= model.Model.CreateTime && o.Id != articalId && o.Culture == Culture).OrderBy(o => o.CreateTime).
                    FirstOrDefault();
            model.NextModel = _articleRepository.Get(o => o.CreateTime <= model.Model.CreateTime && o.Id != articalId && o.Culture == Culture).OrderByDescending(o => o.CreateTime).
            FirstOrDefault();
            Load(model.Model);
            return View(model);
        }
        public ActionResult NotFount()
        {
            var model = CreateFrontViewData<FrontBaseViewData>();
            return View(model);
        }
        public ActionResult TechnologyConsultingControl(string sort = "CreateTime", string order = "DESC")
        {
            var list = _articleRepository.Get(o => o.Culture == Culture).OrderByDescending(o => o.CreateTime).Take(4);
            return View(list);
        }


        /// <summary>
        /// 
        /// </summary>
        public void Load(IArticle model)
        {
            # region 逻辑代码
            //实现思路--将传递过的的参数值和本机IP地址拼成一个有规律的字符串,
            //然后每次拼该字符串之前要做一次判断,
            //看看需要添加进来的字符串（参数值）是否已存在该字符串中,
            //若存在，说明已经执行过该操作了，下一步当然是给出提示了，从而满足我们的需要
            //其中省略了连接数据库后台判断等一些步骤.
            //不过既然是搞程序开发的，相信那些不用我说大家也知道应该在哪里添加判断，呵呵
            string id = "";//声明变量，存储参数id的值
            string newchar = "";//声明中间变量，存储id和IP拼成的字符串
            string userIp = "127.0.0.7";//假设您的IP是127.0.0.7
            //获取客户端IP
            userIp = Request.ServerVariables["HTTP_VIA"] != null ? Request.ServerVariables["HTTP_X_FORWARDED_FOR"].ToString(CultureInfo.InvariantCulture) : Request.ServerVariables["REMOTE_ADDR"].ToString(CultureInfo.InvariantCulture);
            //文本框显示信息
            //将IP地址转成我们想要的字符串格式
            userIp = userIp.Replace(".", "-");
            //接收参数id，一定要加异常处理，因为首次加载的时候cd=null，这里也可以改代码
            id = model.Id;
            //获取或创建cookie(获取和创建其实是一样的，就跟会话一样的)
            HttpCookie myCookie = Request.Cookies["GoodAndBad"];
            //判断获取到的cookie
            if (myCookie == null)//如果cookie还没被创建
            {
                //开始创建cookie
                myCookie = new HttpCookie("GoodAndBad");
                newchar = id + "|" + userIp;//拼字符串，本来应该写成newchar = id+user_IP,但是如果是第一次进来，id=null
                myCookie.Value = newchar;//给我们定义的cookie赋值，这一步很重要，不能少
                //设置过期时间为一天（这里可以修改参数，根据你的需求来定吧）
                myCookie.Expires = DateTime.Now.AddDays(1);
                Response.Cookies.Add(myCookie);//创建新对象并将其添加到 Cookies 集合(这句话不可少)
            }
            else
            {
                //拼字符串-->新字符串 = 处理过的参数值 + 以前的cookie的值（Value属性值）-->注意不是Values
                newchar = myCookie.Value ?? string.Empty;
                //判断处理过的参数值是否已存在cookie中
                int panduannum = newchar.IndexOf(id, StringComparison.Ordinal);
                //如果该参数值已存在，说明一执行过该操作（比如说已顶或踩过某篇文章）
                if (panduannum >= 0)
                {

                }
                else
                {
                    myCookie.Value = id + "|" + newchar;//给我们定义的cookie赋值，这一步很重要，不能少
                    myCookie.Expires = DateTime.Now.AddDays(1);//一天过期（时间可以根据需求设置）
                    Response.Cookies.Add(myCookie);//创建新对象并将其添加到 Cookies 集合(这句话不可少)
                    model.VisitCount += 1;
                    _articleRepository.Save();
                }
            }

            # endregion
        }
    }
}
